#!/bin/bash

# Get all function names for this application.
# Search for the function to ensure they are being used

cd /u/cem/cdc/web
NC='\033[0m' # No Color
Black='\033[0;30m'
DarkGray='\033[1;30m'
Blue='\033[0;34m'
LightBlue='\033[1;34m'
Green='\033[0;32m'
LightGreen='\033[1;32m'
Cyan='\033[0;36m'
LightCyan='\033[1;36m'
Red='\033[0;31m'
LightRed='\033[1;31m'
Purple='\033[0;35m'
LightPurple='\033[1;35m'
BrownOrange='\033[0;33m'
Yellow='\033[1;33m'
LightGray='\033[0;37m'
White='\033[1;37m'

#Default values
searchType="-p" #Default Search type
showSearchedFiles=0
showAllFuncs=0
fileParam=""
scriptName=`basename $0`

filePrefix="$1" #Get parameter
clear && printf '\033[3J' #Clear the screen

function execute {
  fileParam="$(echo -e "${fileParam}" | tr -d '[[:space:]]')" #Remove spaces
  if [[ $showSearchedFiles -eq 1 ]]; then
    showSearchedFiles=0
    echo -e "${Purple}-------------------------------------------${NC}";
    echo -e "Files being searched${NC}";
    grep -rnl --include="*$fileParam*" --exclude="*.swp" --exclude="*.old" \
          "\$Id" *
    echo -e "${Purple}-------------------------------------------${NC}";
  fi

  #Search for all function definition in the files
  grep -rh --include="*$filePrefix*" --exclude="*.swp" "^function " * |
    while read -r line;
  do
    funcUsed=0
    #Remove 'function ' and trailing characters after '('
    func="$( cut -d '(' -f 1 <<< "${line:9}" )";

    if [ $showAllFuncs -eq 1 ]; then
      echo -e "${Blue}$func ${NC}"
    fi

    #Search for function, exclude definition + comment
    while read -r funcCall;
    do
      funcUsed=1
      if [ $showAllFuncs -eq 1 ]; then
        split_grep "$funcCall"
      fi
    done < <(grep -rn --include="*$filePrefix*" --exclude="*.swp" "$func" * |
        grep -v "n $func" | grep -v "\* $func")

    if [ "$funcUsed" -eq 0 ] #if result is != 1, No matches found
     then
      echo -e "${Red} ***  NOT USED  *** ${NC}$func";
    fi
  done
}

function split_grep
{
  IFS=':' read -ra grepArr <<< "$1" #Split string on ':'
  lneNumPos=$(expr ${#grepArr[@]} - 2) #Get the line number position in Array
  matchStringPos=$(expr ${#grepArr[@]} - 1) #Get last position in Array
  matchString=${grepArr[matchStringPos]}
  if [[ $lneNumPos -eq 1 ]]; then
    output="${Purple}${grepArr[0]}:${Green}${grepArr[1]}"
  else
    output="${Green}${grepArr[0]}"
  fi

  lne=$(echo "$matchString" | sed -e 's/^[ \t]*//') #Remove leading spaces
  echo -e "   $output${NC}: $lne";
}


function helper {
  echo -e "${Purple}------------------------------------------------------${NC}"
  echo -e "  Check all functions in the files are being used"
  echo -e "  v1.1"
  echo -e "${Purple}------------------------------------------------------${NC}"
  echo -e "  $scriptName [Files]"
  echo -e "   [Type]  => Type of files to search"
# echo -e "               ${Purple}-f${NC}  Filenames - Search only these "\
#                         "files(Default)"
  echo -e "               ${Purple}-p${NC}  File Prefix - Search all files "\
                          "that contain this text"
  echo -e "   [Files] => List of files, separated by space"
  echo -e "   [opts]  => Optional arguments"
  echo -e "               ${Purple}-d${NC} => List files that were checked"
  echo -e "               ${Purple}-a${NC} => List all function calls"
  echo -e "  Examples"
  echo -e "  $scriptName -p acc_ "
}

#Get Parameters
for arg in "$@"
do
  if [[ "$arg" == *"?"* ]] || [[ "$arg" == *"help"* ]]; then
      helper
      exit
  fi

  case "$arg" in
    -a)
      showAllFuncs=1
    ;;
    -d)
      showSearchedFiles=1
    ;;
    -p|-f)
      searchType="$arg"
    ;;
    *)
      fileParam="$fileParam $arg"
    ;;
  esac
done

if [[ "$filePrefix" == "?" ]] || [[ "$filePrefix" == *"help"* ]]
 then
  helper
elif [[ "$filePrefix" == "" ]]
 then
   echo -e "${Red}Missing parameter !!${NC}"
   helper
else
  execute $filePrefix
fi
